#include <iostream>
#include <dirent.h> //文件系统相关库
#include "LinkTree.h"

void ExploreDirectory(const std::string &path, TreeNode *node) // 扫描文件夹
{
    // 打开文件夹
    DIR *d = opendir(path.c_str());
    if (d == nullptr)
    {
        std::cout << "文件夹路径有误:" << path << std::endl;
        return;
    }
    // 读取文件目录下的文件列表
    dirent *e = nullptr;
    while ((e = readdir(d)) != nullptr)
    {
        if (std::string(e->d_name) == "." || std::string(e->d_name) == "..")
            continue;
        TreeNode *child = new TreeNode(e->d_name);
        child->Contact(node);

        if (e->d_type == DT_DIR)
        {
            ExploreDirectory(path + "/" + std::string(e->d_name), child);
        }
    }
    // 关闭目录流
    closedir(d);
}

void Find(LinkTree& tree, const std::string & name)
{
    DynamicArray a= tree.FindByElement(name);
    for(int i=0; i< a.Size();i++)
    {
        std::cout<<tree.GetNodepath((TreeNode*)a[i])<<std::endl;
    }
}

// argc代表命令行参数数量
// argv代表命令行参数值数组
int main(int argc, char *argv[])
{
    // std::cout<<argc<<std::endl;
    // for(int i=0; i<argc; i++)
    // {
    //     std::cout<<argv[i]<<std::endl;
    // }

    std::string path;
    if (argc < 2)
    {
        path = "./";
    }
    else
    {
        path = argv[1];
    }
    LinkTree tree;
    ExploreDirectory(path, tree.GetRoot());

    // DynamicArray a = tree.FindByElement("1");

    // for (int i = 0; i < a.Size(); i++)
    // {
    //     std::cout << tree.GetNodepath((TreeNode*)a[i]) << std::endl;
    // }

    if(argc>=3)
    {
        Find(tree, argv[2]);
    }
    else{
        std::cout<<"未输入查找的文件名";
    }

    return 0;
}